import { _decorator, Component, Node, tween, Vec3, Tween, input, Input, Director, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Game')
export class Game extends Component {

    @property({ type: Node })
    private aimNode: Node = null;

    @property({ type: Node })
    private ackNode: Node = null;

    @property({ type: Label })
    private overLabel: Label = null;

    private aimTween: Tween<Node> = null;

    private ackTween: Tween<Node> = null;

    private flag: Number = 0;

    @property({ type: Label })
    private scoreLabel: Label = null;

    private score: number = 0;

    start() {
        this.ackInit();
        input.on(Input.EventType.TOUCH_START, this.fire, this);
    }
    ackInit() {
        // 生成随机的y轴位置
        let randomX = Math.random() * 720 - 360; // 生成-640到640之间的随机数

        // 设置ackNode的位置
        this.ackNode.position = new Vec3(randomX, this.ackNode.position.y, 0);

        this.ackNode.active = true;

        this.ackTween = tween(this.ackNode)
                        .to(1, { position: new Vec3(-300, this.ackNode.position.y, 0) })
                        .to(1, { position: new Vec3(300, this.ackNode.position.y, 0) })
                        .union()
                        .repeatForever()
                        .start();
    }

    update(deltaTime: number) {
        this.checkAck();
    }
    checkAck() {
        let dis = Vec3.distance(this.aimNode.position, this.ackNode.position);
        if (dis <= 70) {
            this.aimTween.stop();
            this.aimNode.active = false;
            this.ackNode.active = false;
            this.incrscore();
            this.reLoad();
        }
    }
    reLoad() {
        this.ackInit();
        this.aimNode.position = new Vec3(0,-277.021,0);
        this.aimNode.active = true;        
    }
    incrscore() {
        this.score++;
        this.scoreLabel.string = String(this.score);
    }

    fire() {
        if (this.flag != 0) {
            return;
        }
        this.flag = 1;
        this.aimTween = tween(this.aimNode)
            .to(0.6, { position: new Vec3(0, 550, 0) })
            .call(() => {
                this.over();
            })
            .start();
        this.flag = 0;
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.fire, this);
    }
    
    over(){
        this.overLabel.string = 'Game Over!';
        setTimeout(() => {
            Director.instance.loadScene('Game');
          }, 3000);
    }
}


